package com.sigmatrix.h5.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.sigmatrix.h5.components.FeignManager;
import com.sigmatrix.h5.components.IsvTokenLoader;
import com.sigmatrix.h5.components.RedisClient;
import com.sigmatrix.h5.entity.SmsConfig;
import com.sigmatrix.h5.enums.SmsEventEnum;
import com.sigmatrix.h5.enums.SmsTemplate;
import com.sigmatrix.h5.exception.MessageException;
import com.sigmatrix.h5.utils.Assert;

import so.sao.sms.dto.api.ResponseVO;
import so.sao.sms.dto.api.SmsSendRequestDTO;
import so.sao.sms.dto.api.SmsSendResponseDTO;

/**
 * 短信发送
 * 
 * @author wei.wang
 *
 */
@Service("shortMessageServiceV2")
public class ShortMessageServiceImplV2 extends ShortMessageServiceImpl {

	/**
	 * 短信验证缓存时间。
	 * 
	 * 默认时间单位：TimeUnit.MINUTES
	 */
	private static final int SMS_CACHE_TIME_OUT = 10;// 时间单位：TimeUnit.MINUTES

	@Autowired
	private FeignManager feignManager;

	@Autowired
	private RedisClient redisClient;

	/**
	 * 发送验证码。
	 */
	@Override
	public void sendVerificationCode(String phoneNumber, String eseCode) {
		Assert.notNull(eseCode, "企业code不能为空");
		Assert.notNull(phoneNumber, "手机号不能为空");
		SmsConfig template = smsConfigService.findByModuleAndEseCode(SmsTemplate.REBATE_VER_CODE.toString(), eseCode);
		Assert.notNull(template, "该企业没有开启（配置）短信功能。");
		SmsSendRequestDTO smsReq = new SmsSendRequestDTO();
		// 生成一个6未的随机数
		String code = RandomStringUtils.random(6, "0123456789");
		Map<String,String> keyValues = new HashMap<>();
		keyValues.put("vcode", code);
		smsReq.setEseCode(eseCode);
		smsReq.setEventCode(SmsTemplate.REBATE_VER_CODE.name());
		smsReq.setKeyValues(keyValues);
		smsReq.setPhoneNumbers(Lists.newArrayList(phoneNumber));
		// 发送短信
		ResponseVO<SmsSendResponseDTO> resp = feignManager.sendMessage(smsReq);
		// 保存到redis,设置时效
		redisClient.set(IsvTokenLoader.SMS_CODE_PEFFIX + code, code, SMS_CACHE_TIME_OUT, TimeUnit.MINUTES);
		
		if(resp!=null&&resp.getCode()>0){
			throw new MessageException(resp.getMessage());
		}
	}
	
	
}
